<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Area extends Admin_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->library('pagination');
        $this->load->model('areas_m');
    }

    public function index($page = 1)
    {
        //分页
        $limit                      = 20;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['total_rows']       = $this->areas_m->count_areas();
        $config['base_url']         = base_url('manage/Area/index');
        $config['per_page']         = $limit;
        $config['num_links']        = 1;
        $start                      = ($page - 1) * $limit;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $areas              = $this->areas_m->get_area_list($start, $limit);
        if ($areas) {
            $areas = $this->getTree($areas);
            foreach ($areas as $key => $value) {
                $areas[$key]['area_name'] = str_repeat('┗━', $value['level']) . $value['area_name'];
            }
        }
        $data['areas'] = $areas;
        $this->load->view('areas/index', $data);
    }

    public function add()
    {
        $this->load->view('areas/form');
    }

    public function edit($area_id = null)
    {
        $area = $this->areas_m->findBy(['area_id'=>$area_id]);
        if (!$area) {
            $this->error('参数错误！');
        }
        $data['area']    = $area;
        $data['area_id'] = $area['area_id'];
        $this->load->view('areas/form', $data);
    }

    public function del($area_id)
    {
        if ($area_id) {
            if ($this->areas_m->delete_by(['id' => $area_id])) {
                show_message('恭喜，删除成功', site_url(X_URL . 'Area/index'), 1);
            } else {
                show_message('参数错误', site_url(X_URL . 'Area/index'));
            }
        } else {
            show_message('参数错误', site_url(X_URL . 'Area/index'));
        }
    }

    public function update()
    {

        $post = $this->input->post();
        $area_name = isset($post['area_name']) ? htmlspecialchars($post['area_name'], ENT_QUOTES) : false;
        $area_id   = isset($post['area_id']) ? intval($post['area_id']) : false;
        $area      = [
            'area_name' => $area_name,
        ];
        if (!$area_id) {
            // 新增
            $areas = $this->areas_m->insert($area);
            if ($areas) {
                show_message('新增地区成功', site_url(X_URL . 'Area/index'), 1);
            } else {
                show_message('新增地区失败', site_url(X_URL . 'Area/add'));
            }
        } else {
            // 修改地区信息
            $affected_rows = $this->areas_m->update(['area_id' => $area_id], $area);
            if ($affected_rows) {
                show_message('修改地区成功', site_url(X_URL . 'Area/index'), 1);
            } else {
                show_message('修改地区失败', site_url(X_URL . 'Area/edit'));
            }
        }
    }

    public function getTree($array, $pid = 0, $level = 0)
    {
        //声明静态数组,避免递归调用时,多次声明导致数组覆盖
        static $list = [];
        foreach ($array as $key => $value) {
            //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
            if ($value['parent_id'] == $pid) {
                //父节点为根节点的节点,级别为0，也就是第一级
                $value['level'] = $level;
                //把数组放到list中
                $list[] = $value;
                //把这个节点从数组中移除,减少后续递归消耗
                unset($array[$key]);
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $this->getTree($array, $value['area_id'], $level + 1);
            }
        }
        return $list;
    }

    public function add_son()
    {
        $post              = $this->input->post();
        $data['area_name'] = $post['area_name'];
        $pid               = $post['parent_id'];
        if ($data['area_name'] == '') {
            echo json_encode(['status' => 2, "info" => "地区名称不能为空"]);
            exit();
        }
        if ($pid) {
            $data['parent_id'] = $pid;
            $this->areas_m->insert($data);
            echo json_encode(['status' => 1, "info" => "恭喜，操作成功！"]);
            exit();
        } else {
            echo json_encode(['status' => 2, "info" => "参数缺失"]);
            exit();
        }
    }
    /**
     * 获取省市区联动
     */
    public function get_area()
    {
        $p_id = $this->input->get("p_id");

        $data = $this->areas_m->select(['parent_id' => $p_id]);
        $html = '<option selected="selected" value="0">可选择</option>';
        if (!empty($data)) {
            foreach ($data as $obj) {
                $html .= '<option value="' . $obj['area_id'] . '">' . $obj['area_name'] . '</option>';
            }
        }
        echo $html;
    }
}

